package com.wcy.util;

import com.wcy.util.vo.FileAttribute;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;

@Component
public class FileUploadUtil {
    @Value("${file.uploaddir}")
    private String uploadDir;

    public void tryCreateFolder(){
        try {
            Files.createDirectories(Paths.get(uploadDir));
        } catch (IOException e) {
            throw new RuntimeException("Could not initialize folder for upload!", e);
        }
    }

    public FileAttribute upload(MultipartFile file) {
        try {
            tryCreateFolder();
            String fileName = file.getOriginalFilename();
            assert fileName != null;
            String convertedFileName = "file"+fileName.hashCode()+"."+fileName.substring(fileName.lastIndexOf('.') + 1);
            String filePath = Paths.get(uploadDir, convertedFileName).toString();
            Files.copy(file.getInputStream(), Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);

            FileAttribute fileAttr = new FileAttribute();
            fileAttr.setName(fileName);
            fileAttr.setType(file.getContentType());
            fileAttr.setUrl(convertedFileName);
            fileAttr.setUploadTime(LocalDateTime.now());

            return fileAttr;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public ResponseEntity<byte[]> download(String convertedFileName) {
        try {
            Path file = Paths.get(uploadDir, convertedFileName);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                byte[] bytes = Files.readAllBytes(file);
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(bytes);
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
}


